<?php

namespace App\Http\Controllers\Wechat;

use App\Models\AnswerActivityShare;
use App\Models\TurnActivityShare;
use App\Models\TurnActivityUserUsePrizeRecord;
use App\Validate\UserDrawShareValidate;

/**
 * 用户分享信息
 */
class UserDrawShareController extends CommonController
{
    public $turnActivityShareModel = null;
    public $answerActivityShareModel = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->turnActivityShareModel = new TurnActivityShare();
        $this->answerActivityShareModel = new AnswerActivityShare();
        $this->validate = new UserDrawShareValidate();
    }



    /**
     * 分享获得答题机会
     * @param  token 用户guid
     * @param  act_id 活动id
     * @param  type   类型  1、答题活动   2、在线抽奖
     */
    public function index()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('share')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }
        //判断此活动是否需要邀请码
        $userDrawInviteObj = new UserDrawInviteController();
        $act_info = $userDrawInviteObj->getActInfo($this->request->type, $this->request->act_id);

        if (empty($act_info) || $act_info['end_time'] < date('Y-m-d H:i:s')) {
            return $this->returnApi(202, '活动不存在或已结束');
        }

        $data = [
            'act_id' => $this->request->act_id,
            'user_guid' => $this->request->token,
        ];
        //添加分享记录
        if ($this->request->type == 1) {
            $share_numebr = $this->answerActivityShareModel->change($data);
        } else {
            $share_numebr = $this->turnActivityShareModel->change($data);
        }


        $surplus_prize_number = 1;
        //翻奖还需要判断今日是否有抽奖机会
        if($this->request->type == 2){
            $turnActivityUserUsePrizeRecord = new TurnActivityUserUsePrizeRecord();
            $surplus_prize_number = $turnActivityUserUsePrizeRecord->getSurplusPrizeNumber($this->request->act_id, $this->request->token, $act_info);
        }
        //$surplus_prize_number 未-1 ，今日不可答题，所以不能加
        if (!empty($share_numebr) && $share_numebr <= $act_info['share_number'] && $surplus_prize_number != -1) {
            return $this->returnApi(200, '分享成功', true);
        } else {
            return $this->returnApi(203, '今日分享次数已达上限');
        }
    }
}
